package com.lyc.service.impl;

import com.lyc.dao.ISolrDao;
import com.lyc.dao.ProductMapper;
import com.lyc.entity.Product;
import com.lyc.entity.biz.PCSBiz;
import com.lyc.entity.vo.PCS;
import com.lyc.service.IProductService;
import com.lyc.utils.CollectionUtil;
import org.apache.solr.common.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Transactional
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;

    @Resource(name = "solrDao")
    private ISolrDao solrDao;

    @Override
    public List<Product> getProductsByCid(int cid) {
        return productMapper.selectByCid(cid);
    }

    @Override
    public Product getProductByPid(int pid) {
        Product product = productMapper.selectByPrimaryKey(pid);
        if (product!=null) {
            //对商品详情进行处理
            String description = product.getDescription();
            if (!StringUtils.isEmpty(description)) {
                String[] strArr = description.split("&");
                if (strArr != null && strArr.length > 0) {
                    product.setDescription(strArr[0]);//获取文字叙述部分
                }
            }
        }
        return product;
    }

    @Override
    public List<Product> getAll() {
        return productMapper.selectAll();
    }

    @Override
    public void deleteBatchByPids(List<Integer> pids) {
        //删除solr中对应的商品信息
        for (Integer pid : pids) {
            solrDao.deleteById(pid.toString());
        }
        //删除商品含有的尺码和颜色信息
        productMapper.deleteColorsAndSizesBatchByPids(pids);
        productMapper.deleteBatchByPids(pids);
    }

    @Override
    public void addProduct(Product product) {
        solrDao.addOrUpdateProduct(product);
        productMapper.insertSelective(product);
    }

    @Override
    public void updateProduct(Product product) {
        solrDao.addOrUpdateProduct(product);
        productMapper.updateByPrimaryKeySelective(product);
    }

    @Override
    public Integer getPid() {
        return productMapper.selectLastProductId() + 1;
    }

    @Override
    public Product getProductByPidWithDesc(Integer pid) {
        return productMapper.selectByPrimaryKey(pid);
    }

    @Override
    public List<PCS> getPCSByPid(Integer pid) {
        return productMapper.selectPCSByPid(pid);
    }

    @Override
    public String updateStore(PCSBiz biz) {
        if (biz != null && CollectionUtil.notEmpty(biz.getIds()) && CollectionUtil.notEmpty(biz.getStores())) {
            List<Integer> ids = biz.getIds();
            for (int i = 0; i < ids.size(); i++) {
                productMapper.updateStore(ids.get(i), biz.getStores().get(i));
            }
            return "商品库存更新成功";
        }
        return "商品库存更新失败";
    }
}
